package com.cchip.cloud;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.cchip.cloud.api.MeetingApi;
import com.cchip.cloud.api.MeetingReturned;
import com.cchip.cloud.system.Account;
import com.cchip.cloud.system.BackgroundRunner;
import com.cchip.cloud.system.Config;
import com.cchip.cloud.system.Meeting;

public class LoginActivity extends Activity {

	private CheckBox mSaveAccountCbx = null;
	private CheckBox mAutoLoginCbx = null;
	private EditText mUsernameEtxt = null;
	private EditText mPasswordEtxt = null;
	private Button mRegisterBtn = null;
	private Button mLoginBtn = null;

	private MeetingApi mMeetingApi = MeetingApi.getInstance();
	private Requester mRequester = null;
	private Refresher mRefresher = null;
	private static final int REQ_LOGIN = 10;

	private Activity context = null;
	ProgressDialog mWaitDialog = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		Config.init(this);

		if (Meeting.inMeeting) {
			Intent meeting = new Intent(context, MeetingActivity.class);
			context.startActivity(meeting);
			finish();
		}

		mRequester = new Requester(BackgroundRunner.getRunner());
		mRefresher = new Refresher();

		if (Config.hasSavedAccount()) {
			Account.loadMyAccount();

			if (Config.isAutoLogin()) {
				showWaitDialog();
				mRequester.sendEmptyMessage(REQ_LOGIN);
			}
		} else {
			Account.my.clear();
		}

		setContentView(R.layout.login);

		mSaveAccountCbx = (CheckBox) findViewById(R.id.save_user);
		mAutoLoginCbx = (CheckBox) findViewById(R.id.auto_login);
		mUsernameEtxt = (EditText) findViewById(R.id.username);
		mPasswordEtxt = (EditText) findViewById(R.id.password);
		mRegisterBtn = (Button) findViewById(R.id.register);
		mLoginBtn = (Button) findViewById(R.id.login);

		if (Account.my.name != null)
			mUsernameEtxt.setText(Account.my.name);
		if (Account.my.password != null)
			mPasswordEtxt.setText(Account.my.password);
		if (Config.hasSavedAccount())
			mSaveAccountCbx.setChecked(true);

		mSaveAccountCbx
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						Config.setSavedAccount(isChecked);

						if (!isChecked) {
							mAutoLoginCbx.setChecked(false);
						}
					}

				});

		mAutoLoginCbx.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				Config.setAutoLogin(isChecked);

				if (isChecked) {
					mSaveAccountCbx.setChecked(true);
				}
			}

		});

		mRegisterBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent reg = new Intent(context, RegisterActivity.class);
				context.startActivityForResult(reg, 0);
			}

		});

		mLoginBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Account.my.name = mUsernameEtxt.getText().toString().trim();
				Account.my.password = mPasswordEtxt.getText().toString().trim();
				showWaitDialog();
				mRequester.sendEmptyMessage(REQ_LOGIN);
			}

		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == 1) {
			mUsernameEtxt.setText(Account.my.name);
			mPasswordEtxt.setText(Account.my.password);
		}
	}

	private void showWaitDialog() {
		mWaitDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
		mWaitDialog.setMessage("云会议系统登录中...");
		mWaitDialog.setCancelable(false);
		mWaitDialog.show();
	}

	private class Requester extends Handler {

		public Requester(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			if (msg.what == REQ_LOGIN) {
				MeetingReturned ret = mMeetingApi.login(Account.my.name,
						Account.my.password);
				if (ret != null) {
					switch (ret.operCode) {
					case MeetingReturned.CODE_OK:
						Account.my.roomId = ret.roomId;

						if (mSaveAccountCbx.isChecked()) {
							Config.setUsername(Account.my.name);
							Config.setPassword(Account.my.password);
							Config.setRoomId(Account.my.roomId);
						}

					default:
						mRefresher.sendEmptyMessage(ret.operCode);
						break;
					}
				} else {
					mRefresher
							.sendEmptyMessage(MeetingReturned.CODE_NO_RESPONSE);
				}
			}
		}

	}

	private class Refresher extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			mWaitDialog.cancel();
			String hint = null;
			switch (msg.what) {
			case MeetingReturned.CODE_OK:
				Intent main = new Intent(context, MainActivity.class);
				context.startActivity(main);
				context.finish();
				break;
			case MeetingReturned.CODE_USERNAME_INVALID:
				hint = "用户名中包含非法字符，请重新输入";
				break;
			case MeetingReturned.CODE_PASSWORD_WRONG:
				hint = "密码错误，请重新输入";
				break;
			case MeetingReturned.CODE_NO_RESPONSE:
				hint = "服务器无响应，请稍后再试";
				break;
			}

			if (hint != null) {
				Toast toast = Toast.makeText(context, hint, Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			}

		}

	}

}
